import { Button, Popconfirm, Switch, Radio } from 'antd'
import { Table } from '@/desktop/components'
import { ellipsis } from '@/desktop/styles'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { contactTypeMap } from '@/services/contacts'
import type { Sidebar, CustomSidebar } from '@/services/features/chat-sidebars'
import { Edit } from './edit'

export function ChatSidebars() {
  const [allSidebars] = useStreams(services.features.chatSidebars.list)
  useEffect(() => void services.features.chatSidebars.load(), [])

  const [type, setType] = useState<'custom' | 'system'>('custom')
  const sidebars = useMemo(
    () => allSidebars.filter(v => v.system === (type === 'system')),
    [allSidebars, type],
  )

  function switchStatus(sidebar: Sidebar) {
    void services.features.chatSidebars.addOrUpdate({ ...sidebar, disabled: !sidebar.disabled })
  }
  function remove(sidebar: CustomSidebar) {
    void services.features.chatSidebars.remove(sidebar.id)
  }

  const [editing, setEditing] = useState<true | CustomSidebar | null>(null) // true: 新增  Sidebar: 编辑  null: 空白
  const startEdit = useCallback((target?: CustomSidebar) => setEditing(target ?? true), [])
  const finishEdit = useCallback(() => setEditing(null), [])

  const renderActions = useCallback(
    (sidebar: Sidebar) => {
      if (sidebar.system) return null
      return <div css={styles.actions}>
        <Button type="link" onClick={() => startEdit(sidebar)}>
          编辑
        </Button>
        <Popconfirm title="确认删除此侧边栏吗？" onConfirm={() => remove(sidebar)}>
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>
      </div>
    },
    [startEdit],
  )

  return <>
    <header css={styles.header}>
      <Radio.Group
        buttonStyle="solid"
        value={type}
        onChange={e => setType(e.target.value as typeof type)}
      >
        <Radio.Button value="custom">自定义侧边栏</Radio.Button>
        <Radio.Button value="system">系统侧边栏</Radio.Button>
      </Radio.Group>
    </header>

    {type === 'custom' ? (
      <section css={styles.add}>
        <Button type="primary" onClick={() => startEdit()}>
          添加侧边栏
        </Button>
      </section>
    ) : null}

    <Table<Sidebar>
      rowKey={sidebar => (sidebar.system ? sidebar.key : sidebar.id)}
      dataSource={sidebars}
      scroll={{ y: 300 }}
      pagination={false}
      css={styles.table}
    >
      <Table.Column<Sidebar>
        title="名称"
        width={type === 'custom' ? 180 : undefined}
        dataIndex="name"
      />
      {type === 'custom' ? (
        <Table.Column<Sidebar>
          title="URL"
          width={180}
          dataIndex="url"
          render={url => <div css={styles.url}>{url}</div>}
        />
      ) : null}
      <Table.Column<Sidebar>
        title="范围"
        width={130}
        render={(_, sidebar) => sidebar.scope.map(type => contactTypeMap[type]).join('、')}
      />
      <Table.Column<Sidebar>
        title="状态"
        width={100}
        render={(_, sidebar) => {
          return <Switch
            checked={!sidebar.disabled}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            onChange={() => switchStatus(sidebar)}
          />
        }}
      />
      {type === 'custom' ? (
        <Table.Column<Sidebar> title="操作" key="actions" render={renderActions} width={110} />
      ) : null}
    </Table>

    <Edit editing={editing} onFinish={finishEdit} />
  </>
}

const styles = {
  trigger: css`
    font-size: 13px;
  `,
  header: css`
    padding-top: 6px;
    margin-bottom: 16px;
    text-align: center;
  `,
  add: css`
    margin-bottom: 16px;
  `,
  table: css`
    .ant-table-cell {
      ${ellipsis};
    }
  `,
  url: css`
    ${ellipsis};
    color: #aaa;
  `,
  actions: css`
    button {
      padding: 4px 6px;
      margin-right: 6px;
    }
    button:last-child {
      margin-right: 0;
    }
  `,
}
